#pragma once
#include <iostream>
#include <time.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

#define SIZE 1024
// 定义优先级
#define Info 0
#define Debug 1
#define Warning 2
#define Error 3
#define Fatal 4

// 设置日志往哪里打印
#define Screen 1
#define Onefile 2
#define Classfile 3

#define LogFile "log.txt" // 定义日志文件

class Log
{
public:
  Log()
  {
    printMethod = Screen; // 设置打印方式，默认向显示器打印
    path = "./log/";
  }
  void Enable(int method)
  {
    printMethod = method;
  }
  std::string levelTostring(int level) // 设置可以向不同等级的日志文件打印日志
  {
    switch (level)
    {
    case Info:
      return "Info";
    case Debug:
      return "Debug";
    case Warning:
      return "Warning";
    case Error:
      return "Error";
    case Fatal:
      return "Fatal";
    default:
      return "None";
    }
  }

  void printLog(int level, const std::string &logtxt) // 设置向不同的地方打印日志
  {
    switch (printMethod)
    {
    case Screen:
      std::cout << logtxt << std::endl; // 直接向显示器打印
      break;
    case Onefile:
      printOneFile(LogFile, logtxt);
      break;
    case Classfile:
      printClassFile(level, logtxt);
      break;
    default:
      break;
    }
  }
  void printOneFile(const std::string &logname, const std::string &logtxt)
  {
    std::string _logname = path + logname;                                // path加了一个目录path路径
    int fd = open(_logname.c_str(), O_WRONLY | O_CREAT | O_APPEND, 0666); // 打开这个文件，追加写
    if (fd < 0)
    {
      perror("Error opening file");
      return;
    }
    write(fd, logtxt.c_str(), logtxt.size());
    close(fd);
  }
  void printClassFile(int level, const std::string &logtxt) // 向不同优先级的文件写
  {
    std::string filename = LogFile;
    filename += ".";
    filename += levelTostring(level);
    printOneFile(filename, logtxt);
  }

  ~Log()
  {
  }
  void operator()(int level, const char *format, ...)
  {
    time_t t = time(nullptr); // 获取时间戳
    struct tm *ctime = localtime(&t);
    char leftbuffer[SIZE]; // 左边部分
    snprintf(leftbuffer, sizeof(leftbuffer), "[%s][%d-%d-%d %d:%d:%d]", levelTostring(level).c_str(),
             ctime->tm_year + 1900, ctime->tm_mon + 1, ctime->tm_mday,
             ctime->tm_hour, ctime->tm_min, ctime->tm_sec);

    // 右边部分，可变参数
    va_list s;
    va_start(s, format); // s指向format的下一个
    char rightbuffer[SIZE];
    vsnprintf(rightbuffer, sizeof(rightbuffer), format, s); // 将可变参数写到缓冲区rightbuffer
    va_end(s);
    // 格式：默认部分+自定义部分
    char logtxt[SIZE * 2];
    snprintf(logtxt, sizeof(logtxt), "%s %s\n", leftbuffer, rightbuffer);
    printLog(level, logtxt);
  }

private:
  int printMethod;
  std::string path;
};